package com.example.demo.practice.monitoring;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.example.demo.practice.R;
import com.example.demo.practice.innerclass.IBaseActivity;
import com.example.demo.practice.tool.SoundPlay;
import com.example.demo.practice.tool.TimeAction;
import com.example.demo.practice.ui.MyTempView;

import java.util.Random;

public class TempShow extends IBaseActivity {
    private MyTempView myTempView;
    private MediaPlayer mp;
    private TimeAction timeAction;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int max = 80;
            int min = 30;

            float s = min + ((max - min) * new Random().nextFloat());
            setTemp(s);
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_show);
        //修改标题
        Intent intent = getIntent();
        String code = intent.getStringExtra("code");
        setTitle("温感" + code);
        String company = intent.getStringExtra("company");
        String address = intent.getStringExtra("address");
        TextView textView1 = (TextView) findViewById(R.id.code);
        code = "编号:" + code;
        textView1.setText(code);
        TextView textView2 = (TextView) findViewById(R.id.company);
        company = "单位:" + company;
        textView2.setText(company);
        TextView textView3 = (TextView) findViewById(R.id.address);
        address = "地址:" + address;
        textView3.setText(address);
        myTempView = (MyTempView) findViewById(R.id.timpe);
        setTemp(37.5f);
        timeAction = new TimeAction(handler, 2000);
        timeAction.start();

    }

    /**
     * 更新温度
     *
     * @param temp
     */
    private void setTemp(float temp) {
        myTempView.setTemp(temp, 58, new SoundTempPlay());
    }

    private class SoundTempPlay implements SoundPlay {

        @Override
        public void play() {
            mp = MediaPlayer.create(TempShow.this, R.raw.temp);
            mp.start();
        }
    }

    @Override
    protected void onDestroy() {
        timeAction.stop();
        super.onDestroy();
        handler = null;
        mp=null;
        this.finish();
    }

    @Override
    protected void onPause() {
        timeAction.stop();
        super.onPause();
        handler = null;
        mp=null;
        this.finish();
    }
}
